package com.wcity.manage.web.property;

import com.alibaba.fastjson.JSON;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.utils.*;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.Property;
import com.wcity.manage.dao.model.PropertyPay;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.service.property.PayTypeService;
import com.wcity.manage.service.property.PropertyFeeService;
import com.wcity.manage.service.property.PropertyOnDutyService;
import com.wcity.manage.service.property.PropertyPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 业主缴费数据管理模块
 * Created by zm on 2016/12/9.
 */
@Controller
public class PropertyPayAct {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource private PropertyPayService propertyPayService;
    @Resource private PropertyFeeService propertyFeeService;
    @Resource private PropertyOnDutyService propertyOnDutyService;
    @Resource private PayTypeService payTypeService;

    /**
     * 分页获取表单数据
     * @param pay
     * @param pageModel
     * @param request
     * @return
     */
    @RequestMapping("pay_list")
    public String payList(PropertyPay pay, PageModel pageModel, HttpServletRequest request ){
        try{
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            pay.setUserId(user.getId());
            pageModel.setParams( pay );
            request.setAttribute( "pageModel", pageModel );
            request.setAttribute( "propertyPay", pay );
            request.setAttribute( "userId", user.getId() );
            request.setAttribute( "workNo", user.getWorkNo() );
            request.setAttribute( "typeList",payTypeService.getPayTypeListPage( pageModel ) );
            request.setAttribute( "list", propertyPayService.getUserListPage( pageModel ) );
            request.setAttribute( "blockList", propertyPayService.getblockName( user.getId()) );
        }catch (Exception e){
            e.printStackTrace();
        }

        return "pay/payList";
    }

    /**
     * 转到添加页面
     * @param request
     * @return
     */
    @RequestMapping("to_pay_add")
    public String addPay(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
        request.setAttribute( "blockList", propertyPayService.getblockName(user.getId()) );
        return "pay/addPayList";
    }


    /**
     * 根据小区名称获取缴费类型
     * @param request
     * @return
     */
    @RequestMapping("get_pay_type")
    public @ResponseBody  String getPayType( HttpServletRequest request ){
        Map<String ,Object> map = new HashMap<>();
        try {
            int blockId = Integer.parseInt(request.getParameter("blockName"));
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            Property payType = propertyFeeService.getPayType2(user.getId(),blockId);
            String[] str = payType.getProFeeTypes();
            for(int i = 0;i<str.length;i++){
                System.out.println(str[i]);
                map.put("payType"+i,str[i]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return JSON.toJSONString(map);
    }
    /**
     * 添加
     * @param pay
     * @param request
     * @param response
     */
    @RequestMapping("pay_add")
    public void addPaylist( PropertyPay pay , HttpServletRequest request,HttpServletResponse response ){

        String code = "200";
        String meg = "添加成功";
        try{
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            Block block = propertyOnDutyService.getUserInfo (pay.getBlockId()+"");
            pay.setPayBlockName( block.getBlockName() );
            pay.setUserId(user.getId());
            if(user.getWorkNo() != null){
                pay.setPayProName(user.getWorkNo());
            }else {
                pay.setPayProName("");
            }
            pay.setPayUpdate(new Date());
            pay.setCreateTime( new Date() );
            int success = propertyPayService.addPaylist(pay);
            if( success == 0 ){
                code = "300";
                meg = "添加失败";
            }
        }catch (Exception e) {
            code = "300";
            meg = "添加失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, meg, "pay_list", "", "closeCurrent", ""));
    }

    /**
     * 删除
     * @param request
     * @param response
     */
    @RequestMapping("pay_delect")
    public void delectPay(HttpServletRequest request,HttpServletResponse response){

        String code = "200";
        String meg = "删除成功";
        try{
            String id = request.getParameter("id");
            int success = propertyPayService.delectPay(id);
            if( success == 0 ){
                code = "300";
                meg = "删除失败";
            }
        }catch (Exception e) {
            code = "300";
            meg = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, meg, "pay_list", "", "", ""));
    }

    /**
     * 跳转到修改页面
     * @param request
     * @return
     */
    @RequestMapping("to_pay_edit")
    public String toPayEdit( HttpServletRequest request ){
        String id = request.getParameter("id");
        User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
        PropertyPay list = propertyPayService.getPayInfo( id );
        Property payType = propertyFeeService.getPayType1(user.getId(),list.getPayBlockName());
        request.setAttribute( "blockList", propertyPayService.getblockName(user.getId()) );
        request.setAttribute( "list", list );
        if( payType != null ) {
            request.setAttribute( "payTypes", payType.getProFeeTypes() );
        }
        return "pay/payEdit";
    }

    /**
     * 修改
     * @param
     * @param pay
     * @param response
     */
    @RequestMapping("pay_edit")
    public void payEdit ( PropertyPay pay, HttpServletResponse response ,HttpServletRequest request ) {

        String code = "200";
        String meg = "修改成功";
        try{
            pay.setPayUpdate(new Date());
            Block block = propertyOnDutyService.getUserInfo (pay.getBlockId()+"");
            pay.setPayBlockName( block.getBlockName() );
            int success = propertyPayService.updateUser( pay );
            if( success == 0 ){
                code = "300";
                meg = "修改失败";
            }
        }catch (Exception e) {
            code = "300";
            meg = "修改失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, meg, "pay_list", "", "closeCurrent", ""));
    }

    /**
     * 导出数据到excel
     * @param response
     */
    @RequestMapping("pay_model")
    public void downPayModel(HttpServletRequest request,HttpServletResponse response ,PropertyPay propertyPay) {

        User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
        propertyPay.setUserId(user.getId());

        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        try {
            List<PropertyPay> payModels = propertyPayService.selectPayModel(propertyPay);
            for(int x= 0;x<payModels.size();x++){
                Map<String,Object> a = MapUtil.transBean2Map( payModels.get(x) );
                Map<String, Object> m = new LinkedHashMap<String, Object>();
                Field[] fields = PropertyPay.class.getDeclaredFields();
                SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
                for (int i = 1;i<fields.length;i++){
                    if(fields[i].getName() == "payDate" || fields[i].getName() == "payStartDate"
                            || fields[i].getName() == "payEndDate" || fields[i].getName() == "createTime"||fields[i].getName() == "payUpdate"){
                        Date date=sdf1.parse(a.get(fields[i].getName()).toString());
                        if(fields[i].getName() == "payUpdate"){
                            m.put(fields[i].getName(),DateUtil.getDateTime( date ));
                        }else {
                            m.put(fields[i].getName(), DateUtil.getDate(date));
                        }
                    }else {
                        if(fields[i].getName() != "blockId"&&fields[i].getName() !="userId"){
                            if(fields[i].getName() == "id"){
                                m.put(fields[i].getName(),x+1);
                            }else {
                                m.put(fields[i].getName(), a.get(fields[i].getName()));
                            }
                        }
                    }
                }
                maps.add(m);
            }
            System.out.println(maps);
            String[] title = {"序号","物业名称","小区名称", "物业费户号", "详细地址", "住户姓名", "联系方式", "缴费类型", "收费标准", "应缴金额", "收费日期","缴费状态", "费用开始日期", "费用结束日期", "备注", "更新时间","创建时间"};
            ExcelUtil.exportDataForMap(response,"td_pay", title, maps);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("to_excel_to_db")
    public String toExcelToDb () {
        return "pay/excelToDb";
    }

    @RequestMapping ("excel_to_db")
    public void excelToDb (@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        String code = "200";
        String errMeg ="";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
                        + file.getOriginalFilename();
                logger.error("文件地址：{}"+filePath);
                // 转存文件
                file.transferTo(new File(filePath));
                File target = new File(filePath);
                User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
                errMeg = propertyPayService.excelToDb( target ,user.getId(),user.getWorkNo() );
                if(StringUtil.isBlank(errMeg)){
                    errMeg = "导入成功";
                }else {
                    code = "300";
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(),e);
                errMeg = "服务器异常";
            }
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, errMeg, "pay_list", "", "closeCurrent", ""));
    }
}
